package com.sjz.myfrist;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

/***
 *   Activity 之间传送数据  发送端  点击按钮后可以通过Intent传递数据
 *   带返回值   ActivityResultLauncher新的版本来实现传递
 */
public class ActSendResultActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String mRequest = "i'm here  send info";
    //从Android 10（API级别29）开始，Google推荐使用ActivityResultLauncher替代过时的startActivityForResult方法。
    private ActivityResultLauncher<Intent> register;
    private TextView tv_response;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_send_result);
        TextView tv_request = findViewById(R.id.act_send_result_tv);
        tv_request.setText("待发送的信息："+mRequest);

        tv_response = findViewById(R.id.act_send_response_tv);

        findViewById(R.id.act_send_result_bt).setOnClickListener(this);

        //StartActivityForResult 是最普通的 协议，它使得 registerForActivityResult 用起来就像原先的 onActivityResult 一样。
        //result  acitivity 返回的对象
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if(result != null){
                Intent intent = result.getData();
                if(intent != null && result.getResultCode() == Activity.RESULT_OK){
                    Bundle bundle = intent.getExtras();
                    String response_content = bundle.getString("response_content");
                    String desc = String.format("收到返回消息：%s",response_content);
                    tv_response.setText(desc);
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        Intent intent =new Intent(this,ActReceiveResultActivity.class);//跳转的activity
        //创建一个包裹
        Bundle bundle = new Bundle();
        bundle.putString("request_content",mRequest);
        intent.putExtras(bundle);
        //使用ActivityResultLauncher时，首先需要定义一个ActivityResultLauncher对象，然后通过它的launch()方法来启动Activity或者调用系统功能
        register.launch(intent);
    }
}